<template>
  <div class="work-order-edit page-container">
    <div class="page-header">
      <h2>编辑工单</h2>
      <div>
        <el-button @click="$router.back()">取消</el-button>
        <el-button type="primary" @click="saveWorkOrder" :loading="saving">保存</el-button>
      </div>
    </div>

    <el-card v-loading="loading">
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        class="edit-form"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="工单类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择工单类型">
                <el-option label="维修" value="maintenance" />
                <el-option label="清洁" value="cleaning" />
                <el-option label="安全检查" value="safety" />
                <el-option label="其他" value="other" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="优先级" prop="priority">
              <el-select v-model="form.priority" placeholder="请选择优先级">
                <el-option label="低" value="low" />
                <el-option label="中" value="medium" />
                <el-option label="高" value="high" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择状态">
                <el-option label="待处理" value="pending" />
                <el-option label="已分配" value="assigned" />
                <el-option label="处理中" value="in_progress" />
                <el-option label="已完成" value="completed" />
                <el-option label="已取消" value="cancelled" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="负责人" prop="assignee">
              <el-select v-model="form.assignee" placeholder="请选择负责人" filterable>
                <el-option
                  v-for="user in users"
                  :key="user.id"
                  :label="user.name"
                  :value="user.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="区域">
              <el-select v-model="form.area_id" placeholder="请选择区域" clearable>
                <el-option
                  v-for="area in areas"
                  :key="area.value"
                  :label="area.label"
                  :value="area.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>



        <el-form-item label="备注">
          <el-input
            v-model="form.notes"
            type="textarea"
            :rows="3"
            placeholder="请输入备注（可选）"
          />
        </el-form-item>

        <!-- 自定义字段 -->
        <div v-if="customFields.length > 0">
          <el-divider content-position="left">自定义字段</el-divider>
          <div v-for="field in customFields" :key="field.id">
            <!-- 文本输入 -->
            <el-form-item v-if="field.field_type === 'text'" :label="field.label">
              <el-input
                v-model="customFieldValues[field.name]"
                :placeholder="`请输入${field.label}`"
              />
            </el-form-item>

            <!-- 数字输入 -->
            <el-form-item v-else-if="field.field_type === 'number'" :label="field.label">
              <el-input-number
                v-model="customFieldValues[field.name]"
                :placeholder="`请输入${field.label}`"
                style="width: 100%"
              />
            </el-form-item>

            <!-- 日期选择 -->
            <el-form-item v-else-if="field.field_type === 'date'" :label="field.label">
              <el-date-picker
                v-model="customFieldValues[field.name]"
                type="date"
                :placeholder="`请选择${field.label}`"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>

            <!-- 日期时间选择 -->
            <el-form-item v-else-if="field.field_type === 'datetime'" :label="field.label">
              <el-date-picker
                v-model="customFieldValues[field.name]"
                type="datetime"
                :placeholder="`请选择${field.label}`"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
              />
            </el-form-item>

            <!-- 单选 -->
            <el-form-item v-else-if="field.field_type === 'select'" :label="field.label">
              <el-select
                v-model="customFieldValues[field.name]"
                :placeholder="`请选择${field.label}`"
                style="width: 100%"
              >
                <el-option
                  v-for="option in field.options"
                  :key="option"
                  :label="option"
                  :value="option"
                />
              </el-select>
            </el-form-item>

            <!-- 多选 -->
            <el-form-item v-else-if="field.field_type === 'checkbox'" :label="field.label">
              <el-checkbox-group v-model="customFieldValues[field.name]">
                <el-checkbox
                  v-for="option in field.options"
                  :key="option"
                  :label="option"
                  :value="option"
                >
                  {{ option }}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </div>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { workOrdersApi, areasApi, usersApi } from '@/api'

const route = useRoute()
const router = useRouter()
const loading = ref(false)
const saving = ref(false)
const formRef = ref<FormInstance>()

// 用户列表
const users = ref([])

// 区域列表
const areas = ref([])

// 自定义字段
const customFields = ref([])
const customFieldValues = ref({})

// 表单数据
const form = reactive({
  type: '',
  status: '',
  priority: '',
  assignee: '',
  area_id: '',
  notes: ''
})

// 表单验证规则
const rules: FormRules = {
  type: [
    { required: true, message: '请选择工单类型', trigger: 'change' }
  ],
  priority: [
    { required: true, message: '请选择优先级', trigger: 'change' }
  ]
}

// 加载工单详情
const loadWorkOrder = async () => {
  loading.value = true
  try {
    const id = route.params.id
    const response = await workOrdersApi.getWorkOrder(id)
    const workOrder = response.data.work_order
    
    // 填充表单数据
    Object.assign(form, {
      type: workOrder.type,
      status: workOrder.status,
      priority: workOrder.priority,
      assignee: workOrder.assignee_id, // 使用assignee_id而不是assignee_name
      area_id: workOrder.area_id || '',
      notes: workOrder.notes || ''
    })
    
    // 处理自定义字段数据
    const customFields = workOrder.custom_fields || {}
    const processedCustomFields = {}
    
    // 将API返回的custom_fields格式转换为组件期望的格式
    Object.keys(customFields).forEach(fieldName => {
      const fieldData = customFields[fieldName]
      let value = fieldData.value
      
      // 处理多选字段的数组格式
      if (typeof value === 'string' && value.startsWith('[') && value.endsWith(']')) {
        try {
          value = JSON.parse(value)
        } catch (e) {
          // 如果解析失败，保持原值
          console.warn('Failed to parse custom field value as JSON:', value)
        }
      }
      
      processedCustomFields[fieldName] = value
    })
    
    customFieldValues.value = processedCustomFields
  } catch (error) {
    console.error('加载工单详情失败:', error)
    ElMessage.error('加载工单详情失败')
  } finally {
    loading.value = false
  }
}

// 加载用户列表
const loadUsers = async () => {
  try {
    const response = await usersApi.getUsers({ per_page: 100 }) // 获取前100个用户
    users.value = response.data.users || response.data || []
  } catch (error) {
    console.error('加载用户列表失败:', error)
    ElMessage.error('加载用户列表失败')
  }
}

// 加载区域列表
const loadAreas = async () => {
  try {
    const response = await areasApi.getAreaOptions()
    areas.value = response.data || []
  } catch (error) {
    console.error('加载区域列表失败:', error)
    ElMessage.error('加载区域列表失败')
  }
}

// 加载自定义字段
const loadCustomFields = async () => {
  try {
    const response = await workOrdersApi.getCustomFields()
    customFields.value = response.data.fields
    
    // 初始化自定义字段值
    customFields.value.forEach(field => {
      if (!(field.name in customFieldValues.value)) {
        if (field.field_type === 'checkbox') {
          customFieldValues.value[field.name] = []
        } else {
          customFieldValues.value[field.name] = ''
        }
      }
    })
  } catch (error) {
    console.error('加载自定义字段失败:', error)
  }
}

// 保存工单
const saveWorkOrder = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    saving.value = true
    
    const id = route.params.id
    const updateData = {
      ...form,
      assignee_id: form.assignee, // 将assignee映射为assignee_id
      custom_fields: customFieldValues.value
    }
    
    // 删除前端字段，避免传递无效字段
    delete updateData.assignee
    
    await workOrdersApi.updateWorkOrder(id, updateData)
    
    ElMessage.success('工单更新成功')
    router.push(`/work-orders/${id}`)
  } catch (error) {
    console.error('保存工单失败:', error)
    ElMessage.error('保存工单失败')
  } finally {
    saving.value = false
  }
}

onMounted(async () => {
  loadUsers()
  loadAreas()
  await loadCustomFields() // 先加载自定义字段定义
  loadWorkOrder() // 再加载工单数据
})
</script>

<style scoped>
.work-order-edit {
  width: 100%;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #333;
}

.edit-form {
  max-width: 800px;
}

.el-form-item {
  margin-bottom: 20px;
}

.el-divider {
  margin: 30px 0 20px 0;
}
</style>